package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import ReadWriteXML.CMember;
import ReadWriteXML.ReadXML;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.Controller.ThreadReceiveFile;
import com.application.Controller.ThreadSendFile;

public class FrmChatGroup extends Activity implements OnClickListener,OnKeyListener {
	private static final int SENDFILE = Menu.FIRST+8;
	/*------Biến layout-----------*/
	static MyChatGroupAdapter _myAdapter;
	MyListUserAdapter _myUserListAdapter;
	EditText _edtcontentmessage;
	Button _btnsend;
	Button _btnexit;
	Button _btnSendListGroup;
	Button _btnViewExercise;
	Button _btnSendExercise;
	
	private static int _idDetailLearning;
	private static int _idExercise;
	private static int _idPart;
	private static String _title;
	
	static ListView _lvcontent;
	ListView _lvuser;

	/*-------Biến lưu thông tin chat -------- */
	private String _pathIPList; //đường dẫn file lưu danh sách ip trong nhóm
	private static String _usernameCreater=null;//user name người tạo nhóm
	private String _fNameContentChat = "Group_"+_usernameCreater; //tên file lưu nội dung tin nhắn
	private static String _pathContentChat; //đường dẫn lưu nội dung chat
	static Context _cont;
	private static int _type = 0;//1- chat grouping, 2-chat invite
	static ArrayList<CMember> _memberList = new ArrayList<CMember>(); // danh sách thành viên trong nhóm
	static private ArrayList<String> _messages = new ArrayList<String>(); //nội dung chat
	static private ArrayList<String> _userNameList = new ArrayList<String>();//danh sách userNAme trong nhóm
	static Handler _handleruser = new Handler();
	static protected Runnable _runUpdateMsg;
	static protected Runnable _runUpdateListUser;

	String _textSend;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.frm_chatgroup);

		// ------------gan gia tri cho bien------------
		_cont = this;
		_edtcontentmessage = (EditText) findViewById(R.id.chat_edtcontent);
		_btnsend = (Button) findViewById(R.id.chat_btnsend);
		_lvcontent = (ListView) findViewById(R.id.chat_lvcontent);
		_lvuser = (ListView) findViewById(R.id.chat_listUser);
		_btnexit = (Button) findViewById(R.id.chat_btnexit);

		// -------------lay user name cua nguoi tao-----------------------------
		_pathIPList = ReadWriteFileController.DIRECTORYCHATGROUP + _fNameContentChat+"_grouping_ipList.xml";
		_pathContentChat = ReadWriteFileController.DIRECTORYCHATGROUP +_fNameContentChat + "_grouping_Content.txt";
		_edtcontentmessage.setText("");
		_lvcontent.setDividerHeight(0);

		setListUserAdapter();
		setListAdapter();

		NetworkController.init_runnableUpdateMsgGroup();
		init_runnableUpdateListUser();

		/*---------------------------------------------module 4--------------------------------------*/
		String pathTestGroup = ReadWriteFileController.DIRECTORYTEST + "testListGroup.xml";
		ArrayList<Object> infoTestGroup = ReadXML.ReadTestListGroup(pathTestGroup);
		_idDetailLearning = Integer.valueOf(infoTestGroup.get(1).toString());
		_idPart = Integer.valueOf(infoTestGroup.get(0).toString());
		_idExercise= Integer.valueOf(infoTestGroup.get(2).toString());
		_title= infoTestGroup.get(3).toString();
		Log.d("PEERDROID","title invite chat: " + _title);
		Log.d("PEERDROID","iddetail invite chat: " + _idDetailLearning);
		
		_btnSendListGroup.setVisibility(View.GONE);
		_btnSendExercise.setVisibility(View.GONE);
		_btnViewExercise.setVisibility(View.GONE);
		Log.d("PEERDROID","NetworkController.is_isDoSearchGroup():" + NetworkController.is_isDoSearchGroup());	
		Log.d("PEERDROID","NetworkController.is_isTeamLeader():" + NetworkController.is_isTeamLeader());
		if(NetworkController.is_isDoSearchGroup() && NetworkController.is_isTeamLeader())
		{
			_btnSendListGroup.setVisibility(View.VISIBLE);
		}
		if(NetworkController.is_isDoExericseGroup())
		{
			_btnSendListGroup.setVisibility(View.GONE);
			_btnSendExercise.setVisibility(View.VISIBLE);
			_btnViewExercise.setVisibility(View.VISIBLE);
		}
		
		_btnSendExercise.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(_cont,FrmSelectFile.class);
				intent.putExtra(FrmSelectFile.START_PATH, "/sdcard");
				intent.putExtra("IS_SEND_TEACHER", true);
				startActivityForResult(intent, 1);
			}
		});
		
		_btnSendListGroup.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				NetworkController.SendListMemberToTeacher(1);
			}
		});
		_btnViewExercise.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				ActivityController.getPeerActivity().startActivity(new Intent(ActivityController.getPeerActivity().getBaseContext(),FrmViewExercise.class));
			}
		});
		
		// bat su kien nut send
		_btnsend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					sendMessage();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		// ------ bat su kien khi click len item user---------
		_lvuser.setOnItemClickListener(onItemUserClick);
		// ---------xac dinh su kien enter cho editext chat-------------
		_edtcontentmessage.setOnKeyListener(this);

		// ----------- bat su kien nut exit--------------------
		_btnexit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				for (int i = 0; i < _memberList.size(); i++) {
					NetworkController.SendSignoutGroup(new Address(_memberList.get(i).get_ip().toString()), _usernameCreater);
				}
				
				//xoá file lưu thông tin chat invite
				ReadWriteFileController.deleteFile(_pathIPList);
				ReadWriteFileController.deleteFile(_pathContentChat);
				
				//xoá conversation
				FrmConversation.deleteItemGroup(_usernameCreater);
				finish();

			}
		});


	}

	OnItemClickListener onItemUserClick = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
			// TODO Auto-generated method stub
			String username = _memberList.get(pos).get_userName().toString();
			String fullname = _memberList.get(pos).get_fullName().toString();
			String IP = _memberList.get(pos).get_ip().toString();
			Toast toast = Toast.makeText(getBaseContext(), "User: " + username
					+ "fullname: " + fullname, Toast.LENGTH_SHORT);
			toast.show();

		}
	};

	private static void setListAdapter() {
		_messages.clear();
		Log.d("PEERDROID", "_pathcontentchat: " + _pathContentChat);
		_messages = ReadWriteFileController.ReadTXT(_pathContentChat);
		Log.d("PEERDROID", "_messages: " + _messages);
		if(_messages.size() != 0)
		{
			Log.d("PEERDROID", "_messages group: ");
			_myAdapter = new MyChatGroupAdapter(_cont, _messages);
			_lvcontent.setAdapter(_myAdapter);
		}

	}

	private void setListUserAdapter() {
		_userNameList.clear();
		_memberList = ReadXML.ReadMember(_pathIPList);
		_userNameList = getListUser();
		_myUserListAdapter = new MyListUserAdapter(this, _userNameList);
		_lvuser.setAdapter(_myUserListAdapter);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d("PEERDROID","vao onstart chat group");
		ActivityController.setPeerActivity(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		FrmTabActivity.setTabIndex(1);
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//		ShowSubjectList();	
		Log.d("PEERDROID", "vao resume");
		ActivityController.setPeerActivity(this);
	}

	/**
	 * hàm update danh sách user
	 */
	public static void updateListUser() {
		_handleruser.post(_runUpdateListUser);
	}

	/**
	 * ham set lai noi dung message chat tren list
	 * 
	 * @param acc
	 * @param mess
	 */
	public static void updateMessage() {
		_messages = new ArrayList<String>();
		setListAdapter();
	}

	private static ArrayList<String> getListUser() {
		ArrayList<String> arr = new ArrayList<String>();
		for (int i = 0; i < _memberList.size(); i++) {
			arr.add(_memberList.get(i).get_userName().toString());
		}
		return arr;

	}

	/**
	 * khi xoay man hinh thi noi dung tren list khong bien mat
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	/**
	 * goi khi send messge di, click send
	 * 
	 * @throws IOException
	 */
	private void sendMessage() throws IOException {
		String text = _edtcontentmessage.getText().toString();
		_textSend = NetworkController.get_userName() + "/" + text;

		// set lai message show len list
		if (!text.equals("")) {
			Log.d("PEERDROID", "path write: " + ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + _usernameCreater + "_grouping_Content.txt");
			ReadWriteFileController.writeTXT(ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + _usernameCreater + "_grouping_Content.txt", NetworkController.get_userName() + ": "+ text);
			setListAdapter();
			//cập nhật conversation
			NetworkController.UpdateMessageInConversation(_usernameCreater, text, 3, "", "");
			
			// ---------thuc hien gui thong diep den cac may trong
			// nhom------------
			for (int i = 0; i < _memberList.size(); i++) {
				NetworkController.SendChatMessageGroup(new Address(_memberList.get(i).get_ip().toString()), _textSend, get_usernameCreater(), "group");
			}
			_edtcontentmessage.setText("");
		}
	}

	/**
	 * ham cai dat runnable khi update lai danhs sach user
	 */
	public void init_runnableUpdateListUser() {
		// install runnable
		_runUpdateListUser = new Runnable() {
			@Override
			public void run() {
				setListUserAdapter();
			}
		};
	}

	/**
	 * bat su kien enter khi chat
	 * 
	 * @param v
	 * @param keyCode
	 * @param event
	 * @return
	 */
	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_ENTER:
			try {
				sendMessage();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		try {
			sendMessage();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void set_usernameCreater(String usernameCreater) {
		_usernameCreater = usernameCreater;
	}

	public static String get_usernameCreater() {
		return _usernameCreater;
	}

	public static void set_type(int _type) {
		FrmChatGroup._type = _type;
	}

	public static int get_type() {
		return _type;
	}

	/**
	 * lop adapter cho listview chat group
	 * 
	 */
	private static class MyChatGroupAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Resources mResources;
		private ArrayList<String> mMessages;

		public MyChatGroupAdapter(Context context, ArrayList<String> arrmess) {
			mInflater = LayoutInflater.from(context);
			mResources = context.getResources();
			mMessages = arrmess;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mMessages.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int pos) {
			// TODO Auto-generated method stub
			return pos;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final String messView = mMessages.get(position);
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.row_chatgroup, null);
			}
//			if (messView != null) {
//				String[] sTemp = messView.split(":");
//				String acc = sTemp[0];
//				String mess = getMessage(sTemp);
//				TextView txtContent = (TextView) convertView
//				.findViewById(R.id.rowchatgroup_txtcontent);
//
//				if (acc.equals(NetworkController.get_userName())) {
//					//txtUserName.setTextColor(Color.GRAY);
//					txtContent.setText(Html.fromHtml("<b><font color='#696969' size='14'>" + acc +": " +"</font></b>" + 
//							"<font color='black' size='20'>" + mess + "</font>" ));
//				}else{
//					//txtUserName.setTextColor(Color.BLUE);
//					txtContent.setText(Html.fromHtml("<b><font color='blue' size='14'>" + acc +": " +"</font></b>" + 
//							"<font color='black' size='20'>" + mess + "</font>" ));
//				}
//			}
			if (messView != null) {
				TextView txtContent = (TextView)convertView.findViewById(R.id.rowchatgroup_txtcontent);
				LinearLayout llo = (LinearLayout)convertView.findViewById(R.id.rowchatgroup_lloreceivefile);
				TextView txtFileName = (TextView)convertView.findViewById(R.id.rowchatgroup_txtfilename);
				TextView txtOK = (TextView)convertView.findViewById(R.id.rowchatgroup_txtok);
				TextView txtCancel = (TextView)convertView.findViewById(R.id.rowchatgroup_txtcancel);
				
				String[] sTemp = messView.split(":");
				String mess = getMessage(sTemp);
				String firsttext=sTemp[0];
				
				if(firsttext.equals("##file##")){
					txtContent.setVisibility(View.GONE);
					llo.setVisibility(View.VISIBLE);
					txtCancel.setVisibility(View.VISIBLE);
					txtFileName.setVisibility(View.VISIBLE);
					txtOK.setVisibility(View.VISIBLE);
					//nhan duoc tap tin dinh kem
					String[] content = mess.split("##");
					final String t = content[2];
					final String address = content[3];
					final String port = content[4];
					txtFileName.setText(content[0] + content[1] + content[2]);

					//set su kien khi dong y nhan file
					txtOK.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							Toast toast = Toast.makeText(ActivityController.getPeerActivity(),"Ok", Toast.LENGTH_SHORT);
							toast.show();
							Intent intent = new Intent(ActivityController.getPeerActivity().getBaseContext(), FrmSelectFile.class);
							FrmSelectFile.setFileName(t);
							FrmSelectFile.set_address(address);
							FrmSelectFile.set_port(port);
							FrmSelectFile.set_lineToRemove(messView);
							ActivityController.getPeerActivity().startActivityForResult(intent, 1);
						}
					});
					//set su kien khi khong dong y nhan file
					txtCancel.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							Toast toast = Toast.makeText(ActivityController.getPeerActivity(),"Cancel", Toast.LENGTH_SHORT);
							toast.show();
							
						}
					});
				}

				else{
					txtContent.setVisibility(View.VISIBLE);
					llo.setVisibility(View.GONE);
					txtCancel.setVisibility(View.GONE);
					txtFileName.setVisibility(View.GONE);
					txtOK.setVisibility(View.GONE);
					if(firsttext.equals("##notify##")){
						txtContent.setText(mess);
					}
					//-----------gởi file đi-------------
					else if(firsttext.equals("##sendfile##")){
						txtContent.setText("Bạn gởi đi file: "+ mess);
					}
					else{
						String fullName = sTemp[0];
						if (fullName.equals("Tôi")) {
							txtContent.setText(Html.fromHtml("<b><font color='#696969' size='14'>" + fullName +": " +"</font></b>" + 
									"<font color='black' size='20'>" + mess + "</font>" ));
						}else{
							txtContent.setText(Html.fromHtml("<b><font color='blue' size='14'>" + fullName +": " +"</font></b>" + 
									"<font color='black' size='20'>" + mess + "</font>" ));
						}
					}
				}
			}
			return convertView;
		}
	}
	private static String getMessage(String[] temp) {
		String result = "";
		// i chay tu 2 đe lay ra message
		for (int i = 1; i < temp.length; i++) {
			if (i == temp.length - 1) {
				result = result + temp[i];
			} else {
				result = result + temp[i] + ":";
			}
		}
		return result;
	}

	private class MyListUserAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private Resources mResources;
		private ArrayList<String> mUserList;

		public MyListUserAdapter(Context context, ArrayList<String> userlist) {
			mInflater = LayoutInflater.from(context);
			mResources = context.getResources();
			mUserList = userlist;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mUserList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int pos) {
			// TODO Auto-generated method stub
			return pos;
		}

		@SuppressWarnings("unused")
		private void onBackPressed() {
			// TODO Auto-generated method stub
			FrmTabActivity.get_tabHost().setCurrentTabByTag("Conversation");
			finish();

		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			String userView = mUserList.get(position);
			if (convertView == null) {
				convertView = mInflater
				.inflate(R.layout.row_listuserchat, null);
			}
			if (userView != null) {
				TextView txtUserName = (TextView) convertView
				.findViewById(R.id.row_txtusername);
				txtUserName.setText(userView);
			}
			return convertView;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, SENDFILE, Menu.NONE, "Gửi dữ liệu")
		.setIcon(R.drawable.attach_icon)
		.setAlphabeticShortcut('i');
		return(super.onCreateOptionsMenu(menu));
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case SENDFILE:
			Intent intent = new Intent(this,FrmSelectFile.class);
			intent.putExtra(FrmSelectFile.START_PATH, "/sdcard");
			this.startActivityForResult(intent, 1);
//			startActivity(new Intent(this, FrmSelectFile.class));
			return(true);
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	 public synchronized void onActivityResult(final int requestCode,
             int resultCode, final Intent data) {
		 Log.d("PEERDROID","onActivityResult" );
			if (resultCode == Activity.RESULT_OK) {

				String filePath = data.getStringExtra(FrmSelectFile.RESULT_PATH);
				String type = data.getStringExtra(FrmSelectFile.RESULT_TYPE);
				String address = data.getStringExtra(FrmSelectFile.RESULT_ADDRESS);
				String port = data.getStringExtra(FrmSelectFile.RESULT_PORT);
				String lineToRemove = data.getStringExtra(FrmSelectFile.RESULT_LINETOREMOVE);
				boolean isSendTeacher = data.getBooleanExtra("IS_SEND_TEACHER", false);
				Log.d("PEERDROID","filepath: "+filePath );
				if(type.equals("1"))//luu file
				{
					Log.d("PEERDROID","save file");
					ThreadReceiveFile thread = new ThreadReceiveFile();
					thread.setPathChatFile(ReadWriteFileController.DIRECTORYCHATGROUP +"Group_"+ _usernameCreater + "_grouping_Content.txt");
					String[] temp = filePath.split("/");
					thread.setfName(temp[temp.length - 1]);
					thread.SetReceive(filePath, address, Integer.valueOf(port));
					thread.setLineToRemove(lineToRemove);
					thread.start();
				}
				else if(type.equals("2"))//send file
				{
					Log.d("PEERDROID","send file");
					ArrayList<Address>arrDSGourp = new ArrayList<Address>();
					if(isSendTeacher)
						arrDSGourp.add(new Address(NetworkController.get_ipHost()));
					else
					{
					for (int i = 0; i < _memberList.size(); i++) {
						arrDSGourp.add(new Address(_memberList.get(i).get_ip().toString()));
					}
					}
					ThreadSendFile thread = new ThreadSendFile();
					if(isSendTeacher)
					{
						Log.d("PEERDROID","send file teacher: _idDetailLearning: " + _idDetailLearning);
						Log.d("PEERDROID","send file teacher: _title: " + _title);
						thread.setSendFile(filePath, _usernameCreater, NetworkController.PORT_NUMBER_CURRENT++, _idDetailLearning, _title);
						String fileName = new File(filePath).getName();
						try {
							ReadWriteFileController.writeTXT(ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + _usernameCreater + "_grouping_Content.txt", "##sendfile##: " + fileName);
							setListAdapter();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					else{
						thread.setSendFile(filePath, _usernameCreater, NetworkController.PORT_NUMBER_CURRENT++, "invite", arrDSGourp);
						String fileName = new File(filePath).getName();
						try {
							ReadWriteFileController.writeTXT(ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + _usernameCreater + "_grouping_Content.txt", "##sendfile##: " + fileName);
							setListAdapter();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					thread.start();
				}
			}
     }
}
